from odoo import fields, models, api
from odoo.exceptions import UserError
from ...api.encapsulate.carriers import Carriers


class RPShipPyProConnectTran(models.TransientModel):
    _name = 'rp.shippypro.connect.tran'
    _description = "Shippypro同步瞬态"
    _rec_name = "rpsc_code"

    def _default_auto_rpsc_code(self):
        records = self.env['rp.shippypro.connect.tran'].search([])
        return "RPSC" + str(len(records) + 1).zfill(3)

    rpsc_code = fields.Char(string='索引码', default=_default_auto_rpsc_code, index=True, copy=False, readonly=True)
    create_datetime = fields.Datetime(string='当前时间', default=fields.Datetime.now, copy=False, readonly=True)
    user_id = fields.Many2one(string='操作人', comodel_name='res.users', default=lambda self: self.env.user, copy=False, readonly=True)

    def syn_carriers(self):
        """ 同步承运商信息 """
        rp_courier = self.env['rp.courier'].sudo()
        rp_courier.syn_carriers()
        # flag, carriers_dict = Carriers.get_carriers()  # 调用接口
        # if flag:
        #     # 1、创建/修改承运商
        #     for courier_name, courier_contents in carriers_dict['Carriers'].items():
        #         courier = self.courier_deal(courier_name)
        #         # 2、清掉承运商服务中的shippypro编码
        #         if courier.rp_courier_service_ids:
        #             for s in courier.rp_courier_service_ids:
        #                 s.write({'shippypro_id': False})
                # 3、创建/修改承运商服务
                # for cts in courier_contents:
                #     if cts['Label']:
                #         name = '{}({})'.format(cts['CarrierService'], cts['Label'])
                #     else:
                #         name = cts['CarrierService']
                #     service = self.env['rp.courier.service'].search([('courier_id', '=', courier.id),
                #                                                      ('name', '=', name)])
                #     if not service:
                #         service = self.env['rp.courier.service'].create({'courier_id': courier.id,
                #                                                          'name': name,
                #                                                          'shippypro_id': cts['CarrierID']})
                #     else:
                #         service.write({'shippypro_id': cts['CarrierID']})
        # else:
        #     raise UserError(carriers_dict)

    def courier_deal(self, courier_name):
        """
        判断当前承运商是否存在，不存在则创建
        @param courier_name:承运商名称
        @return: 返回搜索到或者创建出的承运商的rcd(rp.courier)
        """
        courier = self.env['rp.courier'].search([('name', '=', courier_name)])
        if not courier:
            rcd = self.env['rp.courier'].create({'name': courier_name})
            return rcd
        else:
            return courier

    def api_test(self):
        rcd = self.env['rp.ship.order'].search([('code', '=', 'RP_SO/20230307/00006')])
